// 德国T-mobile

// Einzugebende TAN: 6335. Mit der Eingabe der Transaktionsnummer (TAN) lösen Sie einen Bezahlvorgang aus. Geben Sie die TAN niemals an Dritte weiter!
//! 已停止
const puppeteer = require("puppeteer");
const moment = require("moment");

const { createMobile, config } = require("../../../common/mobile");
const {
  info,
  saveFile,
  logging,
  timeout,
  reporter
} = require("../../../common/util");

const name = "tk";
const today = moment().format("YYYY-MM-DD");
const logdir = `./logs/${today}/de/tk/${info.deviceid}`;

const r = reporter(name);
const logger = logging(name, logdir);

(async () => {
  const browser = await puppeteer.launch(config);
  const page = await browser.newPage();

  // 不请求图片
  await page.setRequestInterception(true);
  page.on("request", request => {
    if (request.resourceType() === "image") {
      request.abort();
    } else {
      request.continue();
    }
  });

  const m = await createMobile(page);

  //sub status linstener
  m._page.on("response", response => {
    let url = response.url();
    let status = response.status();

    if (url.startsWith("http")) {
      logger.info(`${response.request().method()}`, status, url);
    }

    if (url.startsWith("https://services.dimoco.at/dcb/AT/mobilkom/redir")) {
      r.s("success");
    }

    if (url.startsWith("http://google.com")) {
      r.w("failure", url);
      m.close();
    }
  });

  //开始
  try {
    r.i("start");

    logger.info("start");

    await m._page.waitForNavigation({ timeout });
    await m.get(`http://offer.lpaosub.com/offer/track?of=1012`);

    logger.info("page1");

    //等待页面加载完成
    await m._page.waitForSelector("button[class='btn btn-warning btn-lg']", {
      timeout
    });

    //保存页面
    saveFile(`${logdir}/1.html`, await m._page.content());

    await m._page.waitForNavigation({ timeout });

    // 第一次点击
    await m._page.evaluate(() => {
      document.getElementsByClassName("btn btn-warning btn-lg")[0].click();
    });

    await r.i("sub_click");
    logger.info("click1");

    await m._page.waitForNavigation({ timeout });

    await m._page.waitForSelector("input[id='otp']", { timeout });
    await m._page.waitForSelector("button[class='btn btn-brand ng-binding']", {
      timeout
    });

    //保存页面
    saveFile(`${logdir}/2.html`, await m._page.content());

    async function parseSms(text) {
      const pattern = /TAN: (\d{4})/;

      const results = pattern.exec(text);

      if (results && results.length >= 2) {
        let code = results[1];

        if (code && code.length === 4 && Number(code)) {
          logger.info(`code - ${code}`);

          await m._page.type("input[id='otp']", code);
          await m._page.evaluate(() => {
            document.getElementById("otp").dispatchEvent(
              new InputEvent("input", {
                inputType: "insertText",
                data: document.getElementById("otp").value,
                dataTransfer: null,
                isComposing: false
              })
            );
          });

          await m.sleep(500);

          // await m._page.evaluate(() => {
          //   document.getElementsByClassName('btn btn-brand ng-binding')[0].click();
          // });

          await r.i("sub_click");
          logger.info("click2");
        } else {
          logger.info("error message");
        }
      }
    }

    await m.sms(parseSms);

    logger.info("end");
    r.i("end");
  } catch (e) {
    saveFile(`${logdir}/error.html`, await m._page.content());
    logger.error(e);
    r.e(e + "");
  } finally {
    await m.close();
  }
  await browser.close();
})();
